package com.echo.yixiaowu.feature.main.home.tab

import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.Crossfade
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridItemSpan
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.pulltorefresh.PullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastForEachIndexed
import coil3.compose.rememberAsyncImagePainter
import coil3.request.ImageRequest
import coil3.request.crossfade
import coil3.size.Size
import com.echo.yixiaowu.feature.components.ImageGridLayout
import com.echo.yixiaowu.feature.components.UserAvatarComponent
import com.echo.yixiaowu.feature.main.home.RecommendState
import com.echo.yixiaowu.route.AppRoute
import kotlinx.serialization.json.Json

@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun RecommendTab(
    modifier: Modifier,
    gridState: LazyStaggeredGridState,
    recommendState: RecommendState,
    sharedTransitionScope: SharedTransitionScope,
    animatedVisibilityScope: AnimatedVisibilityScope,
    onNavigate: (AppRoute) -> Unit,
    onRefresh: () -> Unit,
) {
    val recommends = recommendState.recommendList
    val isLoading = recommendState.fetchBackendDataUiState.isLoading

    LazyVerticalStaggeredGrid(
        modifier = modifier,
        state = gridState,
        columns = StaggeredGridCells.Fixed(1),
        horizontalArrangement = Arrangement.spacedBy(6.dp),
        verticalItemSpacing = 6.dp
    ) {
        when {
            isLoading -> {
                // 骨架屏
                items(9) {
                    RecommendPlaceholder()
                }
            }

            else -> {
                items(items = recommends, key = { recommendItem -> recommendItem.id }) { item ->
                    RecommendItemComp(
                        id = item.id,
                        images = item.url,
                        userName = item.userName,
                        detailData = item.userDetail,
                        itemDescription = item.description,
                        sharedTransitionScope = sharedTransitionScope,
                        animatedVisibilityScope = animatedVisibilityScope,
                        onNavigate = onNavigate
                    )
                }
            }
        }
        item(span = StaggeredGridItemSpan.FullLine) {
            Spacer(
                modifier = Modifier.navigationBarsPadding()
            )
        }
    }
}

@Composable
@Preview
fun RecommendPlaceholder() {
    Card(
        shape = RoundedCornerShape(0.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.background
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
    ) {
        Row(
            modifier = Modifier
                .padding(start = 8.dp, end = 12.dp)
                .fillMaxWidth()
                .background(Color.White),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Box(
                modifier = Modifier
                    .padding(vertical = 6.dp, horizontal = 4.dp)
                    .size(42.dp)
                    .clip(CircleShape)
                    .background(Color.LightGray)
            )

            Column(
                modifier = Modifier
                    .weight(1f)
                    .height(IntrinsicSize.Min),
                verticalArrangement = Arrangement.spacedBy(6.dp)
            ) {
                Box(
                    modifier = Modifier
                        .height(16.dp)
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(4.dp))
                        .background(Color.LightGray)
                )
                Box(
                    modifier = Modifier
                        .height(16.dp)
                        .fillMaxWidth(0.9f)
                        .clip(RoundedCornerShape(4.dp))
                        .background(Color.LightGray)
                )
            }
        }
        Spacer(modifier = Modifier.height(8.dp))
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(16 / 9f)
                .background(Color.LightGray)
        )
    }
}

@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun RecommendItemComp(
    id: String,
    images: List<String>,
    userName: String,
    detailData: String,
    itemDescription: String,
    sharedTransitionScope: SharedTransitionScope,
    animatedVisibilityScope: AnimatedVisibilityScope,
    onNavigate: (AppRoute) -> Unit
) {
    Column(
        modifier = Modifier
            .background(Color.White)
            .padding(horizontal = 16.dp, vertical = 8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        UserAvatarComponent(userName = userName, detailData = detailData)
        Text(
            text = itemDescription
        )
        images.let { imageList ->
            fun onImageClick(index: Int) {
                val pair = imageList.mapIndexed { imageIndex, url -> "img-$id-$imageIndex" to url }
                onNavigate.invoke(
                    AppRoute.Gallery(
                        index = index, imagesJson = Json.encodeToString(pair)
                    )
                )
            }

            ImageGridLayout {
                with(sharedTransitionScope) {
                    imageList.fastForEachIndexed { index, url ->
                        val context = LocalContext.current
                        val imageRequest = rememberAsyncImagePainter(
                            ImageRequest.Builder(context).data(url).crossfade(true)
                                .size(Size(1280, 720)).build()
                        )
                        Image(
                            painter = imageRequest,
                            contentDescription = url,
                            modifier = Modifier
                                .sharedElement(
                                    sharedContentState = rememberSharedContentState("img-$id-$index"),
                                    animatedVisibilityScope = animatedVisibilityScope
                                )
                                .clickable { onImageClick(index) }
                                .aspectRatio(1f)
                                .clip(RoundedCornerShape(4.dp)),
                            contentScale = ContentScale.Crop,
                        )
                    }
                }
            }
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(20.dp)
        )
    }
}

/**
 * 自定义的、可被“拉出”的下拉刷新指示器
 */
@Composable
fun RevealingHeaderIndicator(
    state: PullToRefreshState,
    modifier: Modifier = Modifier,
    isRefreshing: Boolean = false,
    maxHeight: Dp = 80.dp // 头部完全拉出来时的最大高度
) {
    val maxHeightPx = with(LocalDensity.current) { maxHeight.toPx() }

    // 根据下拉的像素距离 state.verticalOffset 来计算当前应该显示的高度
    val currentHeight = state.distanceFraction.coerceAtMost(maxHeightPx)
    val currentHeightDp = with(LocalDensity.current) { currentHeight.toDp() }

    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(currentHeightDp) // 关键点：高度是动态变化的
            .background(Color.Transparent)
            .clipToBounds(),
        contentAlignment = Alignment.Center
    ) {
        // 当下拉超过阈值或者正在刷新时，我们认为是“激活”状态
        val isActivated = state.distanceFraction >= maxHeightPx || isRefreshing

        // 如果正处于刷新状态，显示一个加载动画
        if (isRefreshing) {
            CircularProgressIndicator(
                modifier = Modifier.size(24.dp),
                strokeWidth = 2.dp
            )
        } else {
            // 否则，显示提示文本
            Crossfade(targetState = isActivated, label = "text_fade") { activated ->
                if (activated) {
                    Text("松开以刷新")
                } else {
                    Text("下拉刷新")
                }
            }
        }
    }
}